package com.bwt.top.bwt_ad_flutter.ad;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.bwt.top.ad.bean.AdInfo;
import com.bwt.top.ad.bean.AdSize;
import com.bwt.top.ad.impl.SplashAd;
import com.bwt.top.ad.listener.SplashAdListener;
import com.bwt.top.bwt_ad_flutter.AdErrorUtil;
import com.bwt.top.bwt_ad_flutter.R;
import com.bwt.top.bwt_ad_flutter.config.BwtAdEventConfig;
import com.bwt.top.bwt_ad_flutter.manager.BwtAdManager;
import com.bwt.top.bwt_ad_flutter.model.AdParams;
import com.bwt.top.bwt_ad_flutter.util.LogUtil;
import com.bwt.top.exception.AdError;
import com.bwt.top.util.DisplayUtil;

public class BwtSplashAdActivity extends FragmentActivity {
    private static final String EXTRA_AD_PARAMS = "EXTRA_AD_PARAMS";
    private FrameLayout flContainer;
    private LinearLayout llBottom;
    private ImageView ivBackground;
    private ImageView ivLogo;
    private SplashAd splashAd;
    private int adHeight = 0;
    private boolean ready;
    private boolean readyJump;
    private boolean jumped;

    public static void start(Context context, AdParams adParams) {
        if (context == null || adParams == null) return;
        try {
            Intent intent = new Intent(context, BwtSplashAdActivity.class);
            intent.putExtra(EXTRA_AD_PARAMS, adParams);
            context.startActivity(intent);

            LogUtil.log("开启开屏广告, adId: " + adParams.getAdId());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bwt_splash_ad);

        initView();
        initData();
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        readyJump = true;
        checkJump();
    }

    @Override
    protected void onPause() {
        readyJump = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (splashAd != null) {
            splashAd.release();
            splashAd = null;
        }
        super.onDestroy();
    }

    private void initView() {
        flContainer = findViewById(R.id.flContainer);
        ivBackground = findViewById(R.id.ivBackground);
        llBottom = findViewById(R.id.llBottom);
        ivLogo = findViewById(R.id.ivLogo);
    }

    private void initData() {
        AdParams adParams = (AdParams) getIntent().getSerializableExtra(EXTRA_AD_PARAMS);
        if (adParams == null) {
            finish();
            return;
        }

        initAdView(adParams);
        loadAd(adParams);
    }

    private void initAdView(@NonNull AdParams adParams) {
        setImageRecourse(ivBackground, adParams.getAdBackground());
        boolean success = setImageRecourse(ivLogo, adParams.getAdLogo());

        if (success) {
            llBottom.setVisibility(View.VISIBLE);
            adHeight = DisplayUtil.screenHeight(this) - DisplayUtil.dp2px(156);
        } else {
            adHeight = DisplayUtil.screenHeight(this);
            llBottom.setVisibility(View.GONE);
        }
    }

    private void loadAd(@NonNull AdParams adParams) {
        // 其他相关的配置请参考文档
        splashAd = new SplashAd(this, flContainer);
        splashAd.setAdId(adParams.getPosId());
        splashAd.setSkipViewToTop();
        splashAd.setImmersive(true);

        int adWidth = DisplayUtil.screenWidth(this);
        splashAd.setAdSize(new AdSize(adWidth, adHeight));

        splashAd.setSkipTime(5000L);
        splashAd.setAdListener(new SplashAdListener() {
            @Override
            public void onAdReceive(AdInfo adInfo) {
                LogUtil.log("开屏广告加载成功, adId: " + adParams.getAdId());
                BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_LOAD, adParams);
            }

            @Override
            public void onAdFailed(AdError adError) {
                LogUtil.log("开屏广告加载失败, adId: " + adParams.getAdId() + ", error: " + AdErrorUtil.getError(adError));
                BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_FAILED, adParams, AdErrorUtil.getError(adError));
                readyThenCheckJump();
            }

            @Override
            public void onAdExpose(AdInfo adInfo) {
                LogUtil.log("开屏广告曝光, adId: " + adParams.getAdId());
                BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_EXPOSE, adParams);
            }

            @Override
            public void onAdClick(AdInfo adInfo) {
                LogUtil.log("开屏广告被点击, adId: " + adParams.getAdId());
                BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_CLICK, adParams);
            }

            @Override
            public void onAdClose(AdInfo adInfo) {
                LogUtil.log("开屏广告关闭, adId: " + adParams.getAdId());
                BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_CLOSE, adParams);
                readyThenCheckJump();
            }

            @Override
            public void onAdTick(long l) {

            }

            @Override
            public void onAdSkip(AdInfo adInfo) {
                LogUtil.log("开屏广告跳过点击, adId: " + adParams.getAdId());
                readyThenCheckJump();
            }
        });

        LogUtil.log("开始加载开屏广告, adId: " + adParams.getAdId());
        splashAd.loadAd();
    }

    @SuppressLint("DiscouragedApi")
    private boolean setImageRecourse(ImageView imageView, String resName) {
        if (!TextUtils.isEmpty(resName)) {
            try {
                //得到该图片的id(name 是该图片的名字，"drawable" 是该图片存放的目录，appInfo.packageName是应用程序的包)
                int resID = getResources().getIdentifier(resName, "drawable", getPackageName());
                if (resID <= 0)
                    resID = getResources().getIdentifier(resName, "mipmap", getPackageName());
                if (resID > 0) imageView.setImageResource(resID);
                return true;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    private void readyThenCheckJump() {
        ready = true;
        checkJump();
    }

    private void checkJump() {
        if (ready && readyJump && !jumped) {
            ready = false;
            jumped = true;
            finish();
        }
    }
}
